﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GXRTBTC.PublicClassLibrary.Util
{
    /// <summary>
    /// 输出进度条或等待
    /// </summary>
    public class ConsoleUtility
    {
        const char _block = '.';
        //\b是回退一个字符
        const string _back = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
        const string _twirl = "-\\|/";

        //清行处理操作
        //int currentLineCursor = Console.CursorTop;//记录当前光标位置
        //Console.SetCursorPosition(0, Console.CursorTop);//将光标至于当前行的开始位置
        //Console.Write(new string (' ', Console.WindowWidth));//用空格将当前行填满，相当于清除当前行
        //Console.SetCursorPosition(0, currentLineCursor);//将光标恢复至开始时的位置
        //如果要清除上一行，只需在清行处理操作前将调整光标位置提前一行
        //即：Console.SetCursorPosition(0, Console.CursorTop - 1);。紧接着Console.WriteLine(/*something*/);,即可实现在控制台末尾行重复输出。

        /// <summary>
        /// 百分比进度条显示
        /// </summary>
        /// <param name="percent"></param>
        /// <param name="update"></param>
        public static void WriteProgressBar(int percent, bool update = false)
        {
            if (update)
            { 
                Console.Write(_back);
            }
            Console.Write("[");
            var p = (int)((percent / 10f) + .5f);
            for (var i = 0; i < 10; ++i)
            {
                if (i >= p)
                    Console.Write(' ');
                else
                    Console.Write(_block);
            }
            Console.Write("] {0,3:##0}%", percent);
        }

        /// <summary>
        /// 等待，图标跳动
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="update"></param>
        public static void WriteProgress(int progress, bool update = false)
        {
            if (update)
            { 
                Console.Write("\b");
            }
            Console.Write(_twirl[progress % _twirl.Length]);
        }

        /// <summary>
        /// 覆盖删除，然后显示
        /// </summary>
        /// <param name="line"></param>
        public static void WriteLine(string line)
        {
            Console.SetCursorPosition(0, Console.CursorTop - 1);
            Console.WriteLine(line);
        }

        /// <summary>
        /// 测试
        /// </summary>
        public static void TestProgress()
        {
            ConsoleUtility.WriteProgressBar(0);
            for (var i = 0; i <= 100; ++i)
            {
                ConsoleUtility.WriteProgressBar(i, true);
                Thread.Sleep(50);
            }
            Console.WriteLine();
            ConsoleUtility.WriteProgress(0);
            for (var i = 0; i <= 100; ++i)
            {
                ConsoleUtility.WriteProgress(i, true);
                Thread.Sleep(50);
            }
            Console.WriteLine();
        }
    }
}
